package com.tlkg.qa.redistest.tian;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {

    /**
     * 序列化
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos=null;
        ByteArrayOutputStream baos=null;
        try {
            baos=new ByteArrayOutputStream();
            oos=new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes=baos.toByteArray();

            return bytes;
        } catch(Exception e) {
            return null;
        }
    }

    /**
     * 反序列化
     * @param bytes
     * @return
     */
    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais=null;
        try {
            bais=new ByteArrayInputStream(bytes);
            ObjectInputStream ois=new ObjectInputStream(bais);

            return ois.readObject();
        } catch(Exception e) {
            return null;
        }
    }

    public static Object getObjectFromString(String csv) {
        Object str=null;
        try {
            byte[] objBytes=csv.getBytes("ISO-8859-1");

            if((objBytes == null) || (objBytes.length == 0)) {
                return null;
            }
            ByteArrayInputStream bi=new ByteArrayInputStream(objBytes);
            ObjectInputStream oi=new ObjectInputStream(bi);
            str=oi.readObject();
        } catch(Exception localException) {
        }
        return str;
    }

    public static String getStringFromObject(Object obj) {
        String str="";
        if(obj == null) {
            return null;
        }
        ByteArrayOutputStream bo=new ByteArrayOutputStream();
        try {
            ObjectOutputStream oo=new ObjectOutputStream(bo);

            oo.writeObject(obj);
            str=new String(bo.toByteArray(), "ISO-8859-1");
        } catch(IOException e) {
            e.printStackTrace();
        }
        return str;
    }
}